package com.jetseter.bill.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;


public class JsonUtil {

    public static ObjectMapper objectMapper;

    static {
        objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
    }

    public static <T> T convertToObject(String jsonStr, Class<T> valueType) {

        try {
            if (jsonStr == null || jsonStr == "") {
                return null;
            }
            return objectMapper.readValue(jsonStr, valueType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T convertToObject(String jsonStr, TypeReference<T> valueTypeRef) {
        try {
            if (jsonStr == null || jsonStr == "") {
                return null;
            }
            return objectMapper.readValue(jsonStr, valueTypeRef);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static <T> T convertToObject(String jsonStr, JavaType javaType) {
        try {
            if (jsonStr == null || jsonStr == "") {
                return null;
            }
            return objectMapper.readValue(jsonStr, javaType);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String convertToJson(Object object) {

        try {
            if (object == null) {
                return null;
            }
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static JavaType BuildJavaType(Class<?> c1, Class<?> c2) {
        return objectMapper.getTypeFactory().constructParametricType(c1, c2);
    }


}